//
//  RealTimeView.m
//  mendianjieke
//
//  Created by 响当当 on 7/30/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "RealTimeView.h"
#import "RealTimeCell.h"
#import "NewLoginViewController.h"

@interface RealTimeView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UIView *headView;//企业demo切换
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *infoArr;
@property (nonatomic, strong)NSIndexPath *indexPath;
@property (nonatomic, strong)NSString *type;
@property (nonatomic, assign)NSInteger page;
@end

@implementation RealTimeView

- (UIView *)headView
{
    if (!_headView)
    {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,50*kUIScaleBasePlus)];
        _headView.backgroundColor = LCHexColor(0xFFF3C2);
        
        UILabel *titleLabel = [Utilties creatLabelWithFrame:CGRectMake(15*kUIScaleBasePlus,6.5*kUIScaleBasePlus,23*kUIScaleBasePlus,9.5*kUIScaleBasePlus)
                                               textAligment:NSTextAlignmentLeft
                                                   textClor:LCHexColor(0xB78133)
                                                   textFont:10*kUIScaleBasePlus];
        titleLabel.text = @"位于";
        [_headView addSubview:titleLabel];
        
        UIImageView *rowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame)+5*kUIScaleBasePlus,7.5*kUIScaleBasePlus,13*kUIScaleBasePlus,8*kUIScaleBasePlus)];
        rowImageView.image = [UIImage imageNamed:@"position_arrow"];
        [_headView addSubview:rowImageView];
        
        UILabel *subTitleLabel = [Utilties creatLabelWithFrame:CGRectMake(15*kUIScaleBasePlus,CGRectGetMaxY(titleLabel.frame)+8*kUIScaleBasePlus,150*kUIScaleBasePlus,15.5*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentLeft
                                                      textClor:LCHexColor(0x7F5416)
                                                      textFont:16*kUIScaleBasePlus];
        subTitleLabel.text = @"导购天眼新用户版";
        [_headView addSubview:subTitleLabel];
        
        UIButton *changeDemo = [Utilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(subTitleLabel.frame)+50*kUIScaleBasePlus,10*kUIScaleBasePlus,144*kUIScaleBasePlus,30*kUIScaleBasePlus)
                                                 textAligment:UIControlContentHorizontalAlignmentCenter text:@""
                                                     textClor:[UIColor clearColor]
                                                    buttonBGC:[UIColor clearColor]
                                                     textFont:10*kUIScaleBasePlus
                                                       target:self
                                                       method:@selector(exchangeDemo)];
        [changeDemo setImage:[UIImage imageNamed:@"exchange_login"] forState:UIControlStateNormal];
        [_headView addSubview:changeDemo];
    }
    return _headView;
}


- (NSMutableArray *)infoArr
{
    if (!_infoArr)
    {
        _infoArr = [[NSMutableArray alloc]init];
    }
    return _infoArr;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(10*kUIScaleBasePlus,0,SCREEN_WIDTH-20*kUIScaleBasePlus,SCREEN_HEIGHT-TABBAR_HEIGHT-NAVIBAR_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
        // 设置文字
        [header setTitle:@"加载更多" forState:MJRefreshStateIdle];
        [header setTitle:@"下拉刷新" forState:MJRefreshStatePulling];
//        [header setTitle:@"加载中" forState:MJRefreshStateRefreshing];
        
        // 设置字体
        header.stateLabel.font = [UIFont systemFontOfSize:15];
        header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:12];
        
        // 设置颜色
        header.stateLabel.textColor = LCHexColor(0x989898);
        header.lastUpdatedTimeLabel.textColor = LCHexColor(0x989898);
        
        // 设置刷新控件
        self.tableView.mj_header = header;
        
        //上拉刷新
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewFootData)];
        //设置上拉刷新属性
        [footer setTitle:@"加载更多" forState:MJRefreshStateIdle];
        [footer setTitle:@"加载中" forState:MJRefreshStateRefreshing];
        
        // 设置字体
        footer.stateLabel.font = [UIFont systemFontOfSize:15];
        
        // 设置颜色
        footer.stateLabel.textColor = LCHexColor(0x989898);
        
        _tableView.mj_footer = footer;
    }
    return _tableView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.page = 1;
        if (current_User.isDemoUser.integerValue == 1)
        {
            [self addSubview:self.headView];
            self.tableView.frame = CGRectMake(10*kUIScaleBasePlus,50*kUIScaleBasePlus,SCREEN_WIDTH-20*kUIScaleBasePlus,SCREEN_HEIGHT-TABBAR_HEIGHT-NAVIBAR_HEIGHT-50*kUIScaleBasePlus);
        }
        else
        {
            if (self.headView)
            {
                [self.headView removeFromSuperview];
            }
            
            self.tableView.frame = CGRectMake(10*kUIScaleBasePlus,0,SCREEN_WIDTH-20*kUIScaleBasePlus,SCREEN_HEIGHT-TABBAR_HEIGHT-NAVIBAR_HEIGHT);
        }
        
        
        [self addSubview:self.tableView];
    }
    
    return self;
}

#pragma mark - delegate & datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.infoArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 195*kUIScaleBasePlus;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 38.5*kUIScaleBasePlus;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20*kUIScaleBasePlus,38.5*kUIScaleBasePlus)];
    headView.backgroundColor = [UIColor clearColor];
    
    UILabel *timeLabel = [Utilties creatLabelWithFrame:CGRectMake(0,14.5*kUIScaleBasePlus,SCREEN_WIDTH-20*kUIScaleBasePlus,9.5*kUIScaleBasePlus)
                                          textAligment:NSTextAlignmentCenter
                                              textClor:LCHexColor(0x949494)
                                              textFont:12*kUIScaleBasePlus];
    RealTimeModel *model = [[RealTimeModel alloc]initWithDic:self.infoArr[section]];
    timeLabel.text = [Utilties getTime:model.dataTime.stringValue];
    [timeLabel sizeToFit];
    timeLabel.centerX = self.centerX;
    [headView addSubview:timeLabel];
    
    return headView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    RealTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RealTimeCell"];
    if (!cell)
    {
        cell = [[RealTimeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RealTimeCell"];
        cell.selectionStyle = 0;
    }
    
    if (indexPath.section == 0)
    {
        self.indexPath = indexPath;
    }
    
    RealTimeModel *model = [[RealTimeModel alloc]initWithDic:self.infoArr[indexPath.section]];
    
    cell.model = model;
    
    cell.getCustomerSuccessBlock = ^{
        [self refreshTab];
    };
    
    return cell;
}

#pragma mark - Method
- (void)loadNewData
{
    WeakSelf(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([weakSelf.type isEqualToString:@"0"])
        {
            if (self.reloadDataBlock)
            {
                self.reloadDataBlock();
            }
        }
      
        weakSelf.type = @"0";
        [weakSelf.tableView.mj_header endRefreshing];
    });
}

- (void)loadNewFootData
{
    WeakSelf(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSString *page = [NSString stringWithFormat:@"%ld",weakSelf.page+1];
        weakSelf.page = page.integerValue;
        
        if (weakSelf.foodReloadDataBlock)
        {
            weakSelf.foodReloadDataBlock(page);
        }
        
        [weakSelf.tableView.mj_footer endRefreshing];
        
    });
    
}

- (void)getInfo:(NSArray *)info infoType:(NSString *)type
{
    
    self.page = 1;

    if (info.count > 0)
    {
        self.type = type;
        [self.infoArr removeAllObjects];
        [self.infoArr addObjectsFromArray:info];
        [self.tableView reloadData];
        [self showNewUserGuideIfNeed];
        self.tableView.mj_footer.hidden = NO;
    }
    else
    {
        self.tableView.mj_footer.hidden = YES;
    }
    
}

- (void)getInfoRealTime:(NSArray *)info infoType:(NSString *)type
{
    self.page = 1;
    self.type = type;
    self.infoArr = [NSMutableArray arrayWithArray:info];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView reloadData];
    
     if (info.count > 0)
      {
          dispatch_async(dispatch_get_main_queue(), ^{
               NSIndexPath * dayOne = [NSIndexPath indexPathForRow:0 inSection:0];
               [self.tableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
              self.tableView.mj_footer.hidden = NO;
           });
      }
    else
    {
        self.tableView.mj_footer.hidden = YES;
    }

}

- (void)getRefreshList:(NSArray *)info infoType:(NSString *)type
{
    self.page = 1;

    self.type = type;
    self.infoArr = [NSMutableArray arrayWithArray:info];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView reloadData];

    if (info.count > 0)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
             NSIndexPath * dayOne = [NSIndexPath indexPathForRow:0 inSection:0];
             [self.tableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
            self.tableView.mj_footer.hidden = NO;
         });
    }
    else
    {
        self.tableView.mj_footer.hidden = YES;
    }
}


- (void)getFootRefreshList:(NSArray *)info infoType:(NSString *)type
{
    if (info.count > 0)
    {
        self.type = type;
        [self.infoArr addObjectsFromArray:info];
        [self.tableView reloadData];
    }
    else
    {
        self.tableView.mj_footer.hidden = YES;
    }
}



- (void)refreshTab
{
    if (self.getCustomerSuccessBlock)
    {
        self.getCustomerSuccessBlock();
    }
}


#pragma mark - section不置顶的方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    CGFloat sectionHeaderHeight = 60;
//    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
}


#pragma mark 切换版本
- (void)exchangeDemo
{
        [infoManager logOut:[NSDictionary new]
                     sucess:^(id  _Nonnull acceptData) {
                        current_User.hasLogin = @"0";
                        NewLoginViewController *vc = [[NewLoginViewController alloc]init];
                        vc.type = @"0";
                        [[Utilties getCurrentVC].navigationController presentViewController:vc animated:YES completion:^{
                         }];
                     }
                       fail:^(NSError * _Nullable error) {
                           
                       }];
}

///新手引导,聚光灯
-(void)showNewUserGuideIfNeed
{

///先注释,方便查看效果
  if([NewUserGuide hadShowNewUserGuideForKey:@"stepOne"] || [NewUserGuide isShowingNewUserGuideForKey:@"stepTwo"] || [NewUserGuide isShowingNewUserGuideForKey:@"stepThree"])
    {
        return;
    }
    
    UIView *onView ;
    onView = [UIApplication sharedApplication].keyWindow;
    
    CGRect cellFrame = CGRectZero;
    CGRect expressionFrame = CGRectZero;
    CGRect getFrame = CGRectZero;

    
    if (current_User.isDemoUser.integerValue == 0)
    {
        cellFrame = CGRectMake(5*kUIScaleBasePlus,0*kUIScaleBasePlus,SCREEN_WIDTH-10*kUIScaleBasePlus,233.5*kUIScaleBasePlus);
        
        expressionFrame = CGRectMake(90*kUIScaleBasePlus,18*kUIScaleBasePlus+38.5*kUIScaleBasePlus,20*kUIScaleBasePlus,20*kUIScaleBasePlus);
        
        getFrame = CGRectMake(165*kUIScaleBasePlus,225*kUIScaleBasePlus-50*kUIScaleBasePlus,160*kUIScaleBasePlus,50*kUIScaleBasePlus);
    }
    else
    {
        cellFrame = CGRectMake(5*kUIScaleBasePlus,50*kUIScaleBasePlus,SCREEN_WIDTH-10*kUIScaleBasePlus,233.5*kUIScaleBasePlus);
        
        expressionFrame = CGRectMake(90*kUIScaleBasePlus,19.5*kUIScaleBasePlus+38.5*kUIScaleBasePlus+50*kUIScaleBasePlus,20*kUIScaleBasePlus,20*kUIScaleBasePlus);
        
        getFrame = CGRectMake(165*kUIScaleBasePlus,225*kUIScaleBasePlus,160*kUIScaleBasePlus,50*kUIScaleBasePlus);
    }
    
    
    UIBezierPath *cellPath = [UIBezierPath bezierPathWithRoundedRect:[self convertRect:cellFrame toView:onView] cornerRadius:5];
    UIImage *cellImage = [UIImage imageNamed:@"step_one"];
    
    UIBezierPath *expressionPath = [UIBezierPath bezierPathWithRoundedRect:[self convertRect:expressionFrame toView:onView] cornerRadius:expressionFrame.size.height/2];
    UIImage *expressionImage = [UIImage imageNamed:@"step_two"];
    
    UIBezierPath *getPath = [UIBezierPath bezierPathWithRoundedRect:[self convertRect:getFrame toView:onView] cornerRadius:expressionFrame.size.height/2];
    UIImage *getImage = [UIImage imageNamed:@"step_three"];
      
    CGPoint cellPoint = CGPointMake(0,CGRectGetMaxY(cellFrame)+cellImage.size.height/2+30*kUIScaleBasePlus);
    
    CGPoint expressionPoint = CGPointMake(0,CGRectGetMaxY(expressionFrame)+expressionImage.size.height/2+30*kUIScaleBasePlus);
    
    CGPoint getPoint = CGPointMake(0,CGRectGetMaxY(getFrame)+getImage.size.height/2+30*kUIScaleBasePlus);
    
    NewUserGuide *view = [[NewUserGuide alloc] init];
    
    [view showOn:onView path:cellPath appendPath:YES image:cellImage imageAt:cellPoint withKey:@"stepOne" afterTap:^{
        
        [view showOn:onView path:expressionPath appendPath:YES image:expressionImage imageAt:expressionPoint withKey:@"stepTwo" afterTap:^{
            
               [view showOn:onView path:getPath appendPath:YES image:getImage imageAt:getPoint withKey:@"stepThree" afterTap:^{
                             
                             
                }];
               
           }];
        
    }];
    
}


@end
